//
//  QDPayTypePickerView.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/3/1.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit


protocol QDPayTypeDefaultPickerViewDelegate: class {
    
    /// 绑定新的支付方式
    func bindingNewPayType(in view: QDPayTypeDefaultPickerView)
    /// 选择后的回调
    func payTypePickerView(view: QDPayTypeDefaultPickerView, select type: QDPayType, isCurrent: Bool,indexPath: IndexPath)
}



extension QDPayTypeDefaultPickerViewDelegate {
//    /// 绑定新的支付方式
//    func bindingNewPayType(in view: QDPayTypeDefaultPickerView) {}
//    /// 选择后的回调
//    func payTypePickerView(view: QDPayTypeDefaultPickerView, select type: QDPayType, isCurrent: Bool,indexPath: IndexPath) {}
}


extension QDPayTypeModel {
    
    /// 显示的高度
    var payTypeHeight: CGFloat {
        if discount {
            return 83
        }
        return 55
    }
}


/// 选择默认支付方式的view
final class QDPayTypeDefaultPickerView: NWPopWindow {
    
    /// 底层的白色装载视图
    private let containerView = UIView()
    /// 关闭按钮
    private let closeButton = UIButton()
    /// 标题
    private let titleLabel = UILabel()
    /// 承载提示的视图
    private let subtitleContainerView = UIView()
    /// 提示
    private let subtitleLabel = UILabel()
    /// 列表展示
    private let tableView = UITableView()
    /// 用于强引用
    private var strongSelf: QDPayTypeDefaultPickerView?
    /// 代理对象
    weak var typeDelegate: QDPayTypeDefaultPickerViewDelegate?
    /// 是否启用代理中的isCurrent返回
    var shouldActionIsCurrent: Bool = false
    
    /// 当前签约的支付方式
    var signPayTypes = [QDPayTypeModel]() {
        didSet {
            
            //改变containerView的高度
            let typeHeight = CGFloat(signPayTypes.map { $0.payTypeHeight }.reduce(0, +))//获得所有签约方式的高
            containerView.ritl_height = typeHeight + 60 + 48 + 56 + 16 + BarDistance.TabBar.safeDistance //进行高度的重新计算
            tableView.reloadData() //刷新列表

            //消除选中
            if currentIndex > 0 {
                tableView.deselectRow(at: IndexPath(row: currentIndex, section: 0), animated: false)
            }
            
            currentIndex = -1//回归
            
            // 开始遍历
            for (index,type) in signPayTypes.enumerated() {
                if type.defaultChannel == true {
                    currentIndex = index; break
                }
            }
            
            if currentIndex >= 0 && signPayTypes.count > 0 {//得到默认
                DispatchQueue.main.async {//选中默认
                    self.tableView.selectRow(at: IndexPath(row: self.currentIndex, section: 0), animated: false, scrollPosition: .none)
                }
            }
        }
    }
    
    // 当前默认支付方式选中的index
    private var currentIndex = -1
    
    /// 当前的默认支付方式
    @objc var channelType: String {
        get {
            if currentIndex == -1 || signPayTypes.count == 0 { return "" }
            if currentIndex >= signPayTypes.count { return "" }
            return signPayTypes[currentIndex].payChannel
        }
    }
    
    /// 重置回原来的状态
    func resetOriginPayTypes(){
        
        if currentIndex > 0 { //消除选中
            tableView.deselectRow(at: IndexPath(row: currentIndex, section: 0), animated: false)
        }
        
        let signTypes = self.signPayTypes
        signPayTypes = signTypes
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        containerView.backgroundColor = .white
        containerView.layer.cornerRadius = 16
        containerView.frame = CGRect(x: 0, y: ritl_height, width: ritl_width, height: 363 + containerView.layer.cornerRadius + BarDistance.TabBar.safeDistance)
        
        closeButton.adjustsImageWhenHighlighted = false
        closeButton.setImage("pt_close".namedImage, for: .normal)
        closeButton.addTarget(self, action: #selector(closeButtonDidTap), for: .touchUpInside)
        
        titleLabel.text = "选择默认支付方式"
        titleLabel.font = Font.regular.font(size: 16)
        titleLabel.textColor = QDColors.black
        
        subtitleContainerView.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.9803921569, blue: 0.9725490196, alpha: 1)
        subtitleLabel.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.9803921569, blue: 0.9725490196, alpha: 1)
        subtitleLabel.font = Font.regular.font(size: 14)
        subtitleLabel.textColor = QDColors.gray
        subtitleLabel.text = "优先使用所选支付方式，如支付失败将尝试使用其他方式完成支付"
        subtitleLabel.numberOfLines = 2
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.isScrollEnabled = false
        tableView.separatorStyle = .none
        
        contentView.addSubview(containerView)
        containerView.addSubview(closeButton)
        containerView.addSubview(titleLabel)
        containerView.addSubview(subtitleContainerView)
        subtitleContainerView.addSubview(subtitleLabel)
        containerView.addSubview(tableView)
        
        closeButton.snp.makeConstraints { (make) in
            make.height.width.equalTo(24)
            make.top.equalToSuperview().offset(12)
            make.left.equalToSuperview().offset(16)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.height.equalTo(22)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(13)
        }
        
        subtitleContainerView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(48)
            make.height.equalTo(56)
        }
        
        subtitleLabel.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().inset(20)
        }
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(subtitleContainerView.snp.bottom)
            make.right.left.equalToSuperview()
            make.bottom.equalToSuperview().inset(BarDistance.TabBar.safeDistance)
        }
        
        tableView.contentInset.bottom = hasPhoneHeader() ? 0 : 15
        tableView.register(QDPayTypePickerCell.self, forCellReuseIdentifier: "cell")
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // MARK: Super
    override func showAnimated() {
        
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseIn, animations: {
            self.containerView.ritl_originY = self.ritl_height - self.containerView.ritl_height + self.containerView.layer.cornerRadius - BarDistance.TabBar.safeDistance
        }, completion: nil)
    }
    
    
    override func dismissAnimated() {
        
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
            self.containerView.ritl_originY = self.ritl_height
        }) { (_) in
            self.removeFromSuperview()
        }
    }
    
    /// 立马消失
    @objc func dimissAtOnce(){
        strongSelf = self
        self.containerView.ritl_originY = self.ritl_height
        self.removeFromSuperview()
        strongSelf = nil
    }
    
    // MARK: @objc
    
    /// 关闭按钮点击
    @objc func closeButtonDidTap(){
        dismissAnimated()
    }

}


extension QDPayTypeDefaultPickerView : UITableViewDataSource, UITableViewDelegate {
    

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return signPayTypes.count + 1
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        if let typeCell = cell as? QDPayTypePickerCell {
            
            let maxIndex = signPayTypes.count
            
            //如果是最后一个
            if indexPath.row == maxIndex {
                typeCell.titleLabel.text = "绑定新支付方式"
                typeCell.headerImageView.image = "pt_new".namedImage
                typeCell.selectImageView.image = "pt_select_right_arrow".namedImage//追加新支付方式
                typeCell.reminderLabel.isHidden = true
            }else {//其他的支付方式
                let payTypeModel = signPayTypes[indexPath.row]
                typeCell.reminderLabel.text = payTypeModel.discountMsg
                typeCell.reminderLabel.isHidden = !payTypeModel.discount//根据是否有优惠方式隐藏
                typeCell.titleLabel.text = payTypeModel.type.payTypeTitle
                typeCell.headerImageView.image = payTypeModel.type.payTypeImage.namedImage
            }
            
            /// 赋值
            typeCell.actionSelectAnimated = indexPath.row != maxIndex
            typeCell.bottomLineView.isHidden = (indexPath.row == maxIndex)//最后一行不要下划线
        }
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.row == signPayTypes.count {
            return 60
        }
        
        return signPayTypes[indexPath.row].discount ? 83 : 55 //如果有优惠描述83，没有优惠描述55
    }
    
    
    /// 对最后的绑定新支付方式进行拦截
    func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        
        if indexPath.row == signPayTypes.count  {
            
            typeDelegate?.bindingNewPayType(in: self)//弹出绑定新的支付方式
            return nil
        }
        return indexPath
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        //进行支付方式进行返回即可
        print("点击啦\(indexPath.row)")
//        if !action {
//            action = true; return
//        }
        
        if !shouldActionIsCurrent && indexPath.row == currentIndex  { return }//避免重复回调
        
        typeDelegate?.payTypePickerView(view: self, select: signPayTypes[indexPath.row].type, isCurrent: indexPath.row == currentIndex,indexPath: indexPath)
    }
}
